<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head th:replace="fragments/layout :: header('编辑博客')">
  <title>编辑博客 - 校园综合系统</title>
</head>
<body>
<header th:replace="fragments/layout :: navbar"></header>

<div class="container-fluid">
  <div class="row">
    <div th:replace="fragments/layout :: sidebar('blog-list')"></div>

    <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 main-content">
      <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h1 class="h2">编辑博客</h1>
      </div>

      <form id="editForm" th:object="${blog}">
        <input type="hidden" name="id" th:value="${blog.id}">

        <div class="mb-3">
          <label class="form-label">标题</label>
          <input type="text" class="form-control" name="title" th:value="${blog.title}" required>
        </div>

        <div class="mb-3">
          <label class="form-label">内容</label>
          <textarea class="form-control" name="content" rows="5" th:text="${blog.content}" required></textarea>
        </div>

        <div class="mb-3">
          <label class="form-label">图片URL</label>
          <input type="url" class="form-control" name="image" th:value="${blog.image}">
        </div>

        <button type="submit" class="btn btn-primary">保存修改</button>
        <a th:href="@{/blog}" class="btn btn-secondary">取消</a>
      </form>
    </main>
  </div>
</div>

<div th:replace="fragments/layout :: scripts"></div>
<script>
  // 检查当前用户是否为作者或管理员
  $.get('/api/user/info', function(response) {
    if (response.code === 200) {
      const currentUser = response.data;
      if (currentUser && (currentUser.id === blog.userId || currentUser.role === 1)) {
        $('#blogActions').show(); // 显示编辑/删除按钮
      }
    }
  });

  $(document).ready(function() {
    $('#editForm').submit(function(e) {
      e.preventDefault();

      const formData = {
        id: $('input[name="id"]').val(),
        title: $('input[name="title"]').val(),
        content: $('textarea[name="content"]').val(),
        image: $('input[name="image"]').val()
      };

      $.ajax({
        url: '/api/blog',
        type: 'PUT',
        contentType: 'application/json',
        data: JSON.stringify(formData),
        success: function(response) {
          if (response.code === 200) {
            alert('修改成功');
            window.location.href = '/blog?id=' + formData.id;
          } else {
            alert(response.message || '保存失败');
          }
        },
        error: function() {
          alert('请求失败，请检查网络');
        }
      });
    });
  });
</script>

</body>
</html>